import  UIKit
import  GrowingTextView
import Alamofire
import Toast_Swift
import GradientLoadingBar
import  iOSDropDown

class CompletionTextViewController: UIViewController,GrowingTextViewDelegate{
    var type: Int = 0
    var pageTitle = "文本创作"
    var resultType = 1
    let scrollView = UIScrollView()
    var growingTextView: GrowingTextView!
    var clearButton: UIButton!
    var growingResultTextView: GrowingTextView!
    

    var copyButton: UIButton!
    var completionButton: UIButton!
    var resultTitleLabel: UILabel!
    var resultLabel: UILabel!
//    var tipsLabel: UILabel!
    var containerView: UIView!
    let notchGradientLoadingBar = NotchGradientLoadingBar(
        height: 3.0
    )
    
    var prompt: String!
    var role: String? //角色
    var example: String?
    var menu: String?
    var menu2: String?
    var menu3: String?
    var answer: String?
    
    var optionsMenu = DropDown()
    var optionsMenu2 = DropDown()
    var optionsMenu3 = DropDown()
    
    var menuTitle: String?
    
    var menu2Title: String?
    
    
    var menu3Title: String?
    
    
    var menuLabel = UILabel()
    var menu2Label = UILabel()
    var menu3Label = UILabel()
    
    var menuSelectValue: String?
    var menu2SelectValue: String?
    var menu3SelectValue: String?
    
    var isNeedTextField = false
    
    var retques: DataStreamRequest?
    
    override func viewDidDisappear(_ animated: Bool) {
        stopSSE()
    }
    override func viewDidLoad() {
        navigationItem.title = pageTitle
        view.backgroundColor = primaryDarkBackgroundColor
        view.addSubview(scrollView)
        scrollView.showsVerticalScrollIndicator = false
        scrollView.snp.makeConstraints { (make) in
            make.left.top.right.equalToSuperview()
            make.bottom.equalTo(self.view.safeAreaLayoutGuide.snp.bottom).offset(-56)
        }
        containerView = UIView()
        scrollView.addSubview(containerView)
        containerView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
            make.width.equalTo(UIScreen.main.bounds.width)
        }
        
        view.addSubview(menuLabel)
        view.addSubview(menu2Label)
        view.addSubview(menu3Label)
        
        menuLabel.isHidden = true
        menu2Label.isHidden = true
        menu3Label.isHidden = true
        
        menuLabel.textColor = .lightGray
        menuLabel.font = UIFont.boldSystemFont(ofSize: 15)
        
        menu2Label.textColor = .lightGray
        menu2Label.font = UIFont.boldSystemFont(ofSize: 15)
        
        menu3Label.textColor = .lightGray
        menu3Label.font = UIFont.boldSystemFont(ofSize: 15)
        
        menuLabel.snp.makeConstraints { make in
            make.top.equalTo(containerView.safeAreaLayoutGuide.snp.top).offset(12)
            make.left.equalTo(containerView).offset(16)
        }
        
        menu2Label.snp.makeConstraints { make in
            make.top.equalTo(menuLabel.snp.bottom).offset(28)
            make.left.equalTo(menuLabel)
        }
        
        menu3Label.snp.makeConstraints { make in
            make.top.equalTo(menu2Label.snp.bottom).offset(28)
            make.left.equalTo(menuLabel)
        }
        
        view.addSubview(optionsMenu)
        view.addSubview(optionsMenu2)
        view.addSubview(optionsMenu3)
        optionsMenu.isHidden = true
        optionsMenu2.isHidden = true
        optionsMenu3.isHidden = true
        
        optionsMenu.snp.makeConstraints { make in
            make.centerY.equalTo(menuLabel.snp.centerY)
            make.right.equalTo(containerView).offset(-16)
            make.width.equalTo(UIScreen.main.bounds.width/3)
            make.height.equalTo(32)
        }
        
        
        optionsMenu2.snp.makeConstraints { make in
            make.centerY.equalTo(menu2Label.snp.centerY)
            make.left.equalTo(optionsMenu)
            make.width.equalTo(UIScreen.main.bounds.width/3)
            make.height.equalTo(32)
        }
        
        optionsMenu3.snp.makeConstraints { make in
            make.centerY.equalTo(menu3Label.snp.centerY)
            make.left.equalTo(optionsMenu2)
            make.width.equalTo(UIScreen.main.bounds.width/3)
            make.height.equalTo(32)
        }
        
        let titelLabel = UILabel()
        titelLabel.font = UIFont.boldSystemFont(ofSize: 15)
        titelLabel.textColor = .lightGray
        titelLabel.text = "提示词"
        containerView.addSubview(titelLabel)
        titelLabel.snp.makeConstraints({ make in
            if let menu = menu,menu == ""{
                make.top.equalTo(optionsMenu3.snp.bottom).offset(12)
            }else{
                make.top.equalTo(optionsMenu3.snp.bottom).offset(32)
            }
            make.left.equalTo(containerView).offset(16)
        })
        
        growingTextView = GrowingTextView()
        growingTextView.minHeight = UIScreen.main.bounds.height/5
        growingTextView.maxHeight = UIScreen.main.bounds.height/4
        growingTextView.tintColor = .white
        growingTextView.backgroundColor = primaryBackgroundColor
        growingTextView.placeholder = "请详细描述您的创作要求，越详细越好"
        growingTextView.layer.cornerRadius = 12
        growingTextView.font = UIFont.systemFont(ofSize: 15)
        growingTextView.delegate = self
        containerView.addSubview(growingTextView)
        growingTextView.snp.makeConstraints({ make in
            make.top.equalTo(titelLabel.snp.bottom).offset(12)
            make.left.equalTo(containerView).offset(16)
            make.right.equalTo(containerView).offset(-16)
            make.width.equalTo(UIScreen.main.bounds.width-32)
        })
        
        
        
        clearButton = UIButton(type: .custom)
        clearButton.setTitle((growingTextView.text == nil || growingTextView.text == "") ? "粘贴" :  "清空", for: .normal)
        clearButton.setTitleColor(.primaryColor, for: .normal)
        clearButton.titleLabel?.font = UIFont.systemFont(ofSize: 13, weight: .semibold)
        
        clearButton.isUserInteractionEnabled = true
        clearButton.addTarget(self, action: #selector(handleClearButtonTapped(_:)), for: .touchUpInside)
        containerView.addSubview(clearButton)
        clearButton.snp.makeConstraints({ make in
            make.bottom.equalTo(growingTextView.snp.bottom)
            make.right.equalTo(growingTextView)
            make.width.equalTo(62)
            make.height.equalTo(32)
        })
        
        
        
        resultTitleLabel = UILabel()
        resultTitleLabel.isHidden = true
        resultTitleLabel.font = UIFont.boldSystemFont(ofSize: 15)
        resultTitleLabel.textColor = .white
        resultTitleLabel.text = "生成结果"
        containerView.addSubview(resultTitleLabel)
        resultTitleLabel.snp.makeConstraints({ make in
            make.top.equalTo(growingTextView.snp.bottom).offset(32)
            make.left.equalTo(titelLabel)
        })
        
        
        copyButton = UIButton(type: .custom)
        copyButton.isHidden = true
        copyButton.setTitle("复制", for: .normal)
        copyButton.layer.cornerRadius = 12
        copyButton.setTitleColor(.primaryColor, for: .normal)
        copyButton.titleLabel?.font = UIFont.systemFont(ofSize: 13, weight: .semibold)
        copyButton.layer.borderColor = (UIColor.primaryColor).cgColor
        copyButton.layer.borderWidth = 1
        copyButton.isUserInteractionEnabled = true
        copyButton.addTarget(self, action: #selector(handleCopyButtonTapped(_:)), for: .touchUpInside)
        containerView.addSubview(copyButton)
        copyButton.snp.makeConstraints({ make in
            make.top.equalTo(resultTitleLabel)
            make.right.equalTo(containerView).offset(-16)
            make.width.equalTo(52)
            make.height.equalTo(28)
        })
        
        
        
        growingResultTextView = GrowingTextView()
        growingResultTextView.isHidden = true
        growingResultTextView.minHeight = UIScreen.main.bounds.height/5
        growingResultTextView.maxHeight = UIScreen.main.bounds.height/4
        growingResultTextView.tintColor = .white
        growingResultTextView.backgroundColor = primaryBackgroundColor
        growingResultTextView.layer.cornerRadius = 12
        growingResultTextView.font = UIFont.systemFont(ofSize: 15)
        containerView.addSubview(growingResultTextView)
        growingResultTextView.snp.makeConstraints({ make in
            make.top.equalTo(resultTitleLabel.snp.bottom).offset(24)
            make.left.equalTo(containerView).offset(16)
            make.right.equalTo(containerView).offset(-16)
            make.width.equalTo(UIScreen.main.bounds.width-32)
            
        })
        
        
        
        containerView.snp.makeConstraints({ (make) in
            make.bottom.equalTo(growingResultTextView.snp.bottom)
            
        })
        
        
//        self.view.isUserInteractionEnabled = true
//        self.view.addGestureRecognizer(UITapGestureRecognizer(target:self, action:#selector(self.handleTap(_:))))
//
        
        
        completionButton = UIButton(type: .custom)
        completionButton.setTitle("开始创作", for: .normal)
        completionButton.setTitle("点击停止", for: .selected)
        completionButton.setTitleColor(.white, for: .normal)
        completionButton.setTitleColor(.gray, for: .selected)
        completionButton.layer.cornerRadius = 21
        completionButton.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: .semibold)
        completionButton.frame.size = CGSize(width: 68, height: 20)
        completionButton.backgroundColor = .primaryColor
        completionButton.addTarget(self, action: #selector(handleCompletionButtonTapped(_:)), for: .touchUpInside)
        self.view.addSubview(completionButton)
        completionButton.snp.makeConstraints { make in
            make.centerX.equalTo(self.view)
            make.top.equalTo(self.view.safeAreaLayoutGuide.snp.bottom).offset(-42)
            make.height.equalTo(42)
            make.width.equalTo(UIScreen.main.bounds.width*2/3)
            
        }
        

        
        
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.6){
            self.growingTextView.becomeFirstResponder()
        }
        let toolbar: UIToolbar = UIToolbar(frame: CGRect(x: 0, y: 0,  width: self.view.frame.size.width, height: 30))
        let flexSpace = UIBarButtonItem(barButtonSystemItem:    .flexibleSpace, target: nil, action: nil)
        let doneBtn: UIBarButtonItem = UIBarButtonItem(title: "完成", style: .done, target: self, action: #selector(dismissMyKeyboard))
        toolbar.setItems([flexSpace, doneBtn], animated: false)
        toolbar.sizeToFit()
        growingTextView.inputAccessoryView = toolbar
        
        
        
        //////////解析
        ///
        if let menu = menu,  menu !=  ""{
            if menu.contains("-") && menu.contains("|"){
                let arrays = menu.components(separatedBy: "-")
                menuLabel.text = arrays[0]
                let options = arrays[1].components(separatedBy: "|")
                
                menuSelectValue = options[0]
                self.optionsMenu.isHidden = false
                self.menuLabel.isHidden  = false
                self.optionsMenu.optionArray = options
                self.optionsMenu.text = options[0]
                self.optionsMenu.isSearchEnable = false
                self.optionsMenu.arrowColor = .gray
                self.optionsMenu.textColor = .white
                self.optionsMenu.selectedIndex = 0
                self.optionsMenu.itemsColor = .white
                self.optionsMenu.selectedRowColor = .primaryColor
                self.optionsMenu.arrowSize = 12
                self.optionsMenu.rowBackgroundColor = primaryBackgroundColor
                self.optionsMenu.didSelect{(selectedText , index ,id) in
                    self.menuSelectValue =  selectedText
                    }
                
                
                
            }
        }else{
            
            menuLabel.snp.makeConstraints { make in
                make.top.equalTo(menuLabel.snp.bottom).offset(0)
            }
            
            optionsMenu.snp.makeConstraints { make in
                make.height.equalTo(0)
            }
        }
        
        if let menu2 = menu2,  menu2 !=  ""{
            if menu2.contains("-") && menu2.contains("|"){
                let arrays = menu2.components(separatedBy: "-")
                menu2Label.text = arrays[0]
                let options = arrays[1].components(separatedBy: "|")
                
                menu2SelectValue = options[0]
                self.optionsMenu2.isHidden = false
                self.menu2Label.isHidden  = false
                self.optionsMenu2.optionArray = options
                self.optionsMenu2.text = options[0]
                self.optionsMenu2.isSearchEnable = false
                self.optionsMenu2.arrowColor = .gray
                self.optionsMenu2.textColor = .white
                self.optionsMenu2.selectedIndex = 0
                self.optionsMenu2.itemsColor = .white
                self.optionsMenu2.selectedRowColor = .primaryColor
                self.optionsMenu2.arrowSize = 12
                self.optionsMenu2.rowBackgroundColor = primaryBackgroundColor
                self.optionsMenu2.didSelect{(selectedText , index ,id) in
                    self.menu2SelectValue =  selectedText
                    }
                
                
            }
        }else{
            menu2Label.snp.makeConstraints { make in
                make.top.equalTo(menuLabel.snp.bottom).offset(0)
            }
            optionsMenu2.snp.makeConstraints { make in
                make.height.equalTo(0)
            }
        }
        
        if let menu3 = menu3,  menu3 !=  ""{
            if menu3.contains("-") && menu3.contains("|"){
                let arrays = menu3.components(separatedBy: "-")
                menu3Label.text = arrays[0]
                let options = arrays[1].components(separatedBy: "|")
                
                menu3SelectValue = options[0]
                self.optionsMenu3.isHidden = false
                self.menu3Label.isHidden  = false
                self.optionsMenu3.optionArray = options
                self.optionsMenu3.text = options[0]
                self.optionsMenu3.isSearchEnable = false
                self.optionsMenu3.arrowColor = .gray
                self.optionsMenu3.textColor = .white
                self.optionsMenu3.selectedIndex = 0
                self.optionsMenu3.itemsColor = .white
                self.optionsMenu3.selectedRowColor = .primaryColor
                self.optionsMenu3.arrowSize = 12
                self.optionsMenu3.rowBackgroundColor = primaryBackgroundColor
                self.optionsMenu3.didSelect{(selectedText , index ,id) in
                    self.menu3SelectValue =  selectedText
                    }
                
                
            }
        }else{
            menu3Label.snp.makeConstraints { make in
                make.top.equalTo(menu2Label.snp.bottom).offset(0)
            }
            optionsMenu3.snp.makeConstraints { make in
                make.height.equalTo(0)
            }
        }
        isNeedTextField = self.prompt.contains("{0}")
        
        if let example = example,example != ""{
            growingTextView.placeholder = example
        }
        if !isNeedTextField{
            titelLabel.isHidden = true
            titelLabel.snp.makeConstraints({ make in
               
                    make.top.equalTo(optionsMenu3.snp.bottom).offset(0)
                
                
            })
            growingTextView.isHidden = true
            growingTextView.snp.makeConstraints({ make in
               
                make.height.equalTo(0)
            })
            clearButton.isHidden = true
            clearButton.snp.makeConstraints({ make in
                make.height.equalTo(0)
            })
        }
    }
    
    @objc func dismissMyKeyboard() {
        view.endEditing(true)
    }
    func stopSSE(){
        completionButton.isSelected =  false
        completionButton.backgroundColor = primaryBackgroundColor
        self.notchGradientLoadingBar.fadeOut()
        if let request = self.retques{
            request.cancel()
        }
    }
    
    func startSSE(prompt: String,rolePrompt: String) {
        
        
        var path = "\(baseUrl)chatgpt/chat/sseV2"
        
        if type == 100002{
            //只有type是100002才走文本扩展接口
            path = "\(baseUrl)chatgpt/sseCompletion"
        }
        var components = URLComponents(string: path)
        
        
        
        // 创建URL参数
        let promptItem = URLQueryItem(name: "prompt", value: prompt)
        let rolePromptItem = URLQueryItem(name: "rolePrompt", value: rolePrompt)
       
        
        // 将URL参数添加到URLComponents对象中
        components?.queryItems = [promptItem,rolePromptItem]
        
        
        var receivedData = ""
        var msgIndex = 0
        
        if let url = components?.url {
            // 使用拼接好的URL进行网络请求或其他操作
            print("startSSEstartSSEstartSSE:\(prompt)")
            
            
            self.retques = AFManager.sharedInstance.manager.eventSourceRequest(url, lastEventID: "0").responseEventSource { eventSource in
                switch eventSource.event {
                case .message(let message):
                    if msgIndex == 0{
                        self.growingResultTextView.isHidden = false
                        
                        self.resultTitleLabel.isHidden = false
                        self.copyButton.isHidden = false
                        
                    }
                    msgIndex += 1
                    if let msg = message.data{
                        
                        
                        if msg.isChinese(){
                            receivedData.append("\(msg)")
                        }else{
                            receivedData.append("\(msg) ")
                        }
                        
                    }else{
                        if receivedData != ""{
                            if !receivedData.hasSuffix("\n"){
                                receivedData.append("\n")
                            }
                        }
                    }
                    self.growingResultTextView.text = receivedData
                    if msgIndex % 15 == 0{
                        self.growingResultTextView.scrollToBottom(animated: true)
                    }
                    print("msg=\(message)")
                case .complete(_):
                    self.stopSSE()
                    self.growingResultTextView.scrollToBottom(animated: true)
                    if receivedData.contains(haveNoTryCount) || receivedData.contains(isNotVip){
                        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1){
                            let detailViewController = VipViewController()
                            detailViewController.fromPage = "创作-\(prompt)"
                            self.navigationController?.pushViewController(detailViewController, animated: true)
                        }
                    }
                    print("completion")
                }
            }
        }
    }
    
    @objc private func handleCompletionButtonTapped(_ sender: Any) {
        if let backText = growingTextView.text, backText != "" || !isNeedTextField{
            var tempPrompt:String = self.prompt
            if let value = self.menuSelectValue{
                tempPrompt = tempPrompt.replacingOccurrences(of: "{1}", with: value)
            }
            
            if let value = self.menu2SelectValue{
                tempPrompt = tempPrompt.replacingOccurrences(of: "{2}", with: value)
            }
            
            if let value = self.menu3SelectValue{
                tempPrompt = tempPrompt.replacingOccurrences(of: "{3}", with: value)
            }
            
            if self.prompt.contains("{0}"){
                tempPrompt = tempPrompt.replacingOccurrences(of: "{0}", with: backText)
            }
            
            print("handleCompletionButtonTapped")
            if !completionButton.isSelected{
                completionButton.isSelected =  true
                completionButton.backgroundColor = primaryBackgroundColor
                notchGradientLoadingBar.fadeIn()
                startSSE(prompt: tempPrompt, rolePrompt: role ?? "")
            }else{
               
                stopSSE()
            }
            

        }else{
            self.view.makeToast("请填写提示词",position: .center)
        }
        
        
        
    }
    
    
    
    @objc private func handleClearButtonTapped(_ sender: Any) {
        if let text = growingTextView.text {
            if text == "" {
                let pasteboard = UIPasteboard.general
                if let pasteboardString = pasteboard.string {
                    growingTextView.text = pasteboardString
                    print("粘贴板的内容是：\(pasteboardString)")
                } else {
                    self.view.makeToast("粘贴板没有可用的字符串内容",position: .center)
                    
                    print("粘贴板没有可用的字符串内容")
                }
            }else{
                growingTextView.text = ""
            }
            clearButton.setTitle((growingTextView.text == nil || growingTextView.text == "") ? "粘贴" :  "清空", for: .normal)
        }
        
    }

    
    @objc private func handleCopyButtonTapped(_ sender: Any) {
        if let text = growingResultTextView.text, text !=  ""{
            UIPasteboard.general.string = text
            self.view.makeToast("复制成功",position: .center)
            print("copy")
        }
        
    }
    
    @objc private func handleTap(_ sender: Any) {
        self.view.endEditing(true)
        print("handleTap")
        
    }
    override var wx_titleTextAttributes: [NSAttributedString.Key : Any]? {
        return [NSAttributedString.Key.foregroundColor: UIColor.white]
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
        print("touch began")
    }
    
    
    func textViewDidEndEditing(_ textView: UITextView) {
    }
}

extension UIScrollView {
    func scrollToBottom(animated: Bool) {
        if self.contentSize.height < self.bounds.size.height { return }
        let bottomOffset = CGPoint(x: 0, y: self.contentSize.height - self.bounds.size.height)
        self.setContentOffset(bottomOffset, animated: animated)
    }
}
